package com.fxm.service.jobhandler;

import com.fxm.domain.Rank;
import com.fxm.domain.Record;
import com.fxm.service.RankService;
import com.fxm.service.RecordService;
import com.fxm.utils.TimeUtilCustomize;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 新增每日排行表记录
 * </p>
 *
 * @author fxm
 * @since 2021-02-02
 */
@Component
@Slf4j
public class InsertRankJob {

    @Autowired
    private RankService rankService;

    @Autowired
    private RecordService recordService;

    /**
     * 新增每日排行表记录 每天凌晨12点30分执行一次
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("insertRankJob")
    public ReturnT<String> insertRankJob(String param) throws Exception {
        log.info("新增每日排行表记录任务开始>>>>>>>>>>");

        //拥有答题记录的答题用户
        List<Record> recordList = recordService.listRecordOpenid();

        //答题记录数据不存在 任务执行失败
        if (Objects.isNull(recordList) || recordList.size() == 0) {
            return ReturnT.FAIL;
        }

        //转化为openid集合
        List<String> openidList = recordList.stream().map(v -> v.getOpenid()).collect(Collectors.toList());

        //新增答题排行表当天数据
        for (String openid : openidList) {

            Rank rank = Rank.builder()
                    .openid(openid)
                    .maxCorrect(0)
                    .maxError(0)
                    .maxNum(0)
                    .todayNum(0)
                    .totalNum(0)
                    .build();

            //根据openid和date日期 查询当天该用户rank表数据是否存在
            Rank rankByOpenidAndDate = rankService.getRankByOpenidAndDate(openid,
                    TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_DAY_FORMAT, new Date()));

            //当天该用户rank表数据不存在 则新增
            if (Objects.isNull(rankByOpenidAndDate)) {
                rankService.insertRank(rank);
            }
        }

        log.info("新增每日排行表记录任务结束<<<<<<<<<<");
        return ReturnT.SUCCESS;
    }

}
